<?php
namespace UserSystem\Driver\Cache;

use UserSystem\Config;

/**
 * @author: wangxi
 * @desc: memcached 缓存类
 * Date: 15-2-4
 */
class Memcache
{
    private $_mmc;

    public function __construct()
    {
        try {
            //TODO: 优先加载 memcached
            if (extension_loaded('memcached')) {
                $this->_mmc = new \Memcached();
            }
            else if(extension_loaded('memcache')){
                $this->_mmc = new \Memcache();
            }
            else{
                throw new \Exception('memcache extension not loaded for php');

            }
        } catch (\Exception $e) {
            exit($e->getMessage());
        }

        //加载memcached 配置
        $conf = Config::getInstance()->get('memcached');

        foreach ($conf as $name => $cache_server) {
            if (!array_key_exists('hostname', $cache_server)) {
                $cache_server['hostname'] = $conf['default']['default_host'];
            }

            if (!array_key_exists('port', $cache_server)) {
                $cache_server['port'] = $conf['default']['default_port'];
            }

            if (!array_key_exists('weight', $cache_server)) {
                $cache_server['weight'] = $conf['default']['default_weight'];
            }

            $this->_mmc->addServer($cache_server['hostname'], $cache_server['port'], $cache_server['weight']);
        }

    }

    /**
     * 获取key
     * @param $id
     * @return bool
     */
    public function get($id)
    {
        $data = $this->_mmc->get($id);

        return (is_array($data)) ? $data[0] : false;
    }

    /**
     * 设置key
     * @param     $id
     * @param     $data
     * @param int $ttl
     * @return bool
     */
    public function save($id, $data, $ttl = 60)
    {
        if (get_class($this->_mmc) == 'Memcached') {
            return $this->_mmc->set($id, array($data, time(), $ttl), $ttl);
        }
        else {
            if (get_class($this->_mmc) == 'Memcache') {
                return $this->_mmc->set($id, array($data, time(), $ttl), 0, $ttl);
            }
        }

        return false;
    }

    /**
     * 删除key
     * @param $id
     * @return bool
     */
    public function rm($id)
    {
        return $this->_mmc->delete($id);
    }

    public function clean()
    {
        return $this->_mmc->flush();
    }

    public function getInfo()
    {
        return $this->_mmc->getStats();
    }

    public function getMetadata($id)
    {
        $stored = $this->_mmc->get($id);

        if (count($stored) !== 3) {
            return false;
        }

        list($data, $time, $ttl) = $stored;

        return array(
            'expire' => $time + $ttl,
            'mtime'  => $time,
            'data'   => $data
        );
    }

}